package cn.initcap.concurrency.concurrency.thread;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.concurrent.TimeUnit;

/**
 * 使用动态代理
 *
 * @author initcap
 * @date Created in 2018/7/25 PM2:43.
 */
public class ConnectionDriver {

    private static final String COMMIT = "commit";

    /**
     * 创建一个Connection的代理，在commit时休眠100毫秒
     *
     * @return 连接
     */
    public static final Connection createConnection() {
        return (Connection) Proxy.newProxyInstance(ConnectionHandler.class.getClassLoader(),
                new Class<?>[]{Connection.class}, new ConnectionHandler());
    }

    static class ConnectionHandler implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (COMMIT.equals(method.getName())) {
                TimeUnit.MICROSECONDS.sleep(100);
            }
            return null;
        }
    }
}
